<template>
  <div class="document-space">
    <div class="space-header">
      <h3>📚 文档空间</h3>
      <div class="space-controls">
        <button @click="showCreateSpaceDialog" class="create-btn">
          ➕ 新增空间
        </button>
        <button @click="refreshSpaces" class="refresh-btn" :disabled="loading">
          {{ loading ? '加载中...' : '🔄' }}
        </button>
      </div>
    </div>

    <!-- 空间选择下拉框 -->
    <div class="space-selector">
      <el-select
        v-model="selectedSpaceId"
        @change="handleSpaceChange"
        placeholder="请选择文档空间"
        :loading="loading"
        loading-text="加载空间列表中..."
        style="width: 100%"
        size="large"
        clearable
      >
        <el-option
          v-for="space in spaces"
          :key="space.id"
          :label="`${space.name} (${space.documentCount})`"
          :value="space.id"
        >
          <div class="space-option">
            <div class="space-info">
              <span class="space-name">{{ space.name }}</span>
              <span class="space-desc" v-if="space.description">{{ space.description }}</span>
            </div>
            <div class="space-right">
              <div class="space-color" v-if="space.color" :style="{ backgroundColor: space.color }"></div>
              <span class="space-count">{{ space.documentCount }}</span>
            </div>
          </div>
        </el-option>
      </el-select>
    </div>

    <div v-if="loading && spaces.length === 0" class="loading">
      <p>⏳ 正在加载...</p>
    </div>

    <div v-else-if="spaces.length === 0" class="empty-state">
      <p>📭 暂无空间</p>
      <p>请先创建一个文档空间</p>
    </div>

    <div v-else-if="selectedSpaceId && selectedSpace" class="space-info">
      <div class="space-details">
        <h4 :style="{ color: selectedSpace.color || '#42b883' }">
          {{ selectedSpace.name }}
        </h4>
        <p v-if="selectedSpace.description" class="space-description">
          {{ selectedSpace.description }}
        </p>
        <p class="space-stats">
          📄 {{ selectedSpace.documentCount }} 个文档
        </p>
      </div>
      <div class="space-actions">
        <button @click="showCreateDocumentDialog" class="create-doc-btn">
          ➕ 新增文档
        </button>
        <button @click="emitSpaceSelected" class="view-docs-btn">
          👁️ 查看文档
        </button>
      </div>
    </div>

    <!-- 新增空间弹窗 -->
    <div v-if="showSpaceDialog" class="dialog-overlay" @click="closeSpaceDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>新增文档空间</h3>
          <button @click="closeSpaceDialog" class="close-btn">✕</button>
        </div>
        <form @submit.prevent="submitSpaceForm" class="dialog-form">
          <div class="form-group">
            <label for="spaceName">空间名称：</label>
            <input
              id="spaceName"
              v-model="spaceFormData.name"
              type="text"
              placeholder="请输入空间名称"
              required
              class="form-input"
            />
          </div>
          <div class="form-group">
            <label for="spaceDescription">空间描述：</label>
            <textarea
              id="spaceDescription"
              v-model="spaceFormData.description"
              placeholder="请输入空间描述（可选）"
              class="form-input form-textarea"
            ></textarea>
          </div>
          <div class="form-group">
            <label for="spaceColor">空间颜色：</label>
            <input
              id="spaceColor"
              v-model="spaceFormData.color"
              type="color"
              class="form-input color-input"
            />
          </div>
          <div class="dialog-actions">
            <button type="button" @click="closeSpaceDialog" class="cancel-btn">取消</button>
            <button type="submit" :disabled="submitting" class="submit-btn">
              {{ submitting ? '保存中...' : '创建' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 新增文档弹窗 -->
    <div v-if="showDocumentDialog" class="dialog-overlay" @click="closeDocumentDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>新增文档</h3>
          <button @click="closeDocumentDialog" class="close-btn">✕</button>
        </div>
        <form @submit.prevent="submitDocumentForm" class="dialog-form">
          <div class="form-group">
            <label for="name">文档名称：</label>
            <input
              id="name"
              v-model="documentFormData.name"
              type="text"
              placeholder="请输入文档名称"
              required
              class="form-input"
            />
          </div>
          <div class="form-group">
            <label for="content">文档内容：</label>
            <textarea
              id="content"
              v-model="documentFormData.content"
              placeholder="请输入文档内容（可选）"
              class="form-input form-textarea"
            ></textarea>
          </div>
          <div class="form-group">
            <label for="parentId">父文档：</label>
            <select
              id="parentId"
              v-model="documentFormData.parentId"
              class="form-input form-select"
              :disabled="loadingParentOptions"
            >
              <option :value="null">无父文档（根节点）</option>
              <option
                v-for="option in parentOptions"
                :key="option.id"
                :value="option.id"
              >
                {{ option.name }}
              </option>
            </select>
            <p v-if="loadingParentOptions" class="loading-text">加载中...</p>
          </div>
          <div class="dialog-actions">
            <button type="button" @click="closeDocumentDialog" class="cancel-btn">取消</button>
            <button type="submit" :disabled="submitting" class="submit-btn">
              {{ submitting ? '保存中...' : '创建' }}
            </button>
          </div>
        </form>
      </div>
    </div>
    
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { documentApi, namespaceApi } from '../services/api'
import type { DocumentOption } from '../types/document'
import type { NameSpace, CreateNameSpaceRequest } from '../types/namespace'
import { toast } from '../utils/message'

// Props
const props = defineProps<{
  currentSpaceId?: number | null
}>()

// 定义事件
const emit = defineEmits<{
  spaceSelect: [spaceId: number]
  documentCreate: [spaceId: number]
}>()

// 空间相关状态
const spaces = ref<NameSpace[]>([])
const selectedSpaceId = ref<number | null>(null)
const loading = ref(false)

// 空间弹窗相关状态
const showSpaceDialog = ref(false)
const submitting = ref(false)
const spaceFormData = ref<CreateNameSpaceRequest>({
  name: '',
  description: '',
  color: '#42b883',
  sortNo: 0
})

// 文档弹窗相关状态
const showDocumentDialog = ref(false)
const documentFormData = ref({
  name: '',
  content: '',
  parentId: null as number | null,
  sortNo: 0
})

// 父文档选项相关状态
const parentOptions = ref<DocumentOption[]>([])
const loadingParentOptions = ref(false)


// 计算属性
const selectedSpace = computed(() => {
  return selectedSpaceId.value ? spaces.value.find(s => s.id === selectedSpaceId.value) : null
})

const fetchSpaces = async (): Promise<void> => {
  try {
    loading.value = true
    spaces.value = await namespaceApi.getAll()
    
    // 如果有传入的当前空间ID，使用它
    if (props.currentSpaceId && spaces.value.find(s => s.id === props.currentSpaceId)) {
      selectedSpaceId.value = props.currentSpaceId
    } else if (!selectedSpaceId.value && spaces.value.length > 0) {
      // 如果没有指定空间且有空间列表，选择第一个
      selectedSpaceId.value = spaces.value[0].id
      // 触发空间选择事件
      emit('spaceSelect', spaces.value[0].id)
    }
  } catch (err: any) {
    console.error('获取空间列表失败:', err)
    
    let errorMessage = ''
    if (err.code === 'ECONNREFUSED' || err.code === 'ERR_NETWORK') {
      errorMessage = '无法连接到服务器，请检查网络连接'
    } else if (err.response?.status === 404) {
      errorMessage = 'API接口未找到，请检查服务器配置'
    } else if (err.response?.status >= 500) {
      errorMessage = '服务器错误，请稍后重试'
    } else {
      errorMessage = `连接失败: ${err.response?.data?.message || err.message}`
    }
    
    // 使用toast显示错误，而不是在页面中显示
    toast.error(errorMessage)
  } finally {
    loading.value = false
  }
}

const refreshSpaces = (): void => {
  fetchSpaces()
}

// 空间选择变化处理
const handleSpaceChange = (): void => {
  if (selectedSpaceId.value) {
    // 触发空间选择事件
    emit('spaceSelect', selectedSpaceId.value)
  }
}

// 空间弹窗方法
const showCreateSpaceDialog = (): void => {
  spaceFormData.value = { name: '', description: '', color: '#42b883', sortNo: 0 }
  showSpaceDialog.value = true
}

const closeSpaceDialog = (): void => {
  showSpaceDialog.value = false
  spaceFormData.value = { name: '', description: '', color: '#42b883', sortNo: 0 }
  submitting.value = false
}

const submitSpaceForm = async (): Promise<void> => {
  submitting.value = true
  
  try {
    const newSpace = await namespaceApi.create(spaceFormData.value)
    spaces.value.push(newSpace)
    selectedSpaceId.value = newSpace.id
    toast.success('空间创建成功')
    closeSpaceDialog()
  } catch (err: any) {
    console.error('创建空间失败:', err)
    const errorMsg = getErrorMessage(err)
    toast.error(`创建空间失败: ${errorMsg}`)
  } finally {
    submitting.value = false
  }
}

// 文档弹窗方法
const showCreateDocumentDialog = (): void => {
  if (!selectedSpaceId.value) {
    toast.warning('请先选择一个空间')
    return
  }
  documentFormData.value = { name: '', content: '', parentId: null, sortNo: 0 }
  showDocumentDialog.value = true
  fetchParentOptions()
}

const closeDocumentDialog = (): void => {
  showDocumentDialog.value = false
  documentFormData.value = { name: '', content: '', parentId: null, sortNo: 0 }
  submitting.value = false
  parentOptions.value = []
}

const submitDocumentForm = async (): Promise<void> => {
  if (!selectedSpaceId.value) {
    toast.error('请选择空间')
    return
  }
  
  // 通知父组件创建文档
  emit('documentCreate', selectedSpaceId.value)
  closeDocumentDialog()
}

// 查看文档按钮 - 触发空间选择事件
const emitSpaceSelected = (): void => {
  if (selectedSpaceId.value) {
    emit('spaceSelect', selectedSpaceId.value)
  }
}

// 获取父文档选项
const fetchParentOptions = async (excludeId?: number): Promise<void> => {
  if (!selectedSpaceId.value) return
  
  try {
    loadingParentOptions.value = true
    // 这里需要根据空间获取文档列表来构建父文档选项
    const documents = await documentApi.getByNamespace(selectedSpaceId.value)
    parentOptions.value = documents
      .filter(doc => doc.id !== excludeId && doc.parentId !== excludeId)
      .map(doc => ({
        id: doc.id,
        name: doc.name,
        content: doc.content
      }))
  } catch (err: any) {
    console.log('获取父文档选项失败，使用空列表:', err.message)
    parentOptions.value = []
  } finally {
    loadingParentOptions.value = false
  }
}


// 错误消息处理工具函数
const getErrorMessage = (err: any): string => {
  if (err.response?.data?.message) {
    return err.response.data.message
  }
  
  if (err.response?.status) {
    const statusMap: Record<number, string> = {
      400: '请求参数错误',
      401: '未授权访问',
      403: '权限不足',
      404: '资源不存在',
      409: '数据冲突',
      422: '数据验证失败',
      500: '服务器内部错误',
      502: '网关错误',
      503: '服务暂不可用'
    }
    
    return statusMap[err.response.status] || `请求失败 (${err.response.status})`
  }
  
  if (err.code === 'ECONNREFUSED' || err.code === 'ERR_NETWORK') {
    return '网络连接失败'
  }
  
  if (err.code === 'ENOTFOUND') {
    return 'DNS解析失败'
  }
  
  if (err.code === 'ETIMEDOUT') {
    return '请求超时'
  }
  
  return err.message || '未知错误'
}


// 暴露方法供父组件调用
defineExpose({
  refreshSpaces,
  showCreateSpaceDialog,
  showCreateDocumentDialog
})

// 监听传入的当前空间ID变化
watch(() => props.currentSpaceId, (newSpaceId) => {
  if (newSpaceId && spaces.value.find(s => s.id === newSpaceId)) {
    selectedSpaceId.value = newSpaceId
  }
})

onMounted(() => {
  fetchSpaces()
})
</script>

<style scoped>
.document-space {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  background: white;
  border-bottom: 1px solid #e1e1e1;
  min-height: 280px;
  max-height: 400px;
}

.space-header {
  padding: 1rem;
  border-bottom: 1px solid #e1e1e1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.space-header h3 {
  margin: 0;
  color: #42b883;
  font-size: 1.1rem;
}

.space-controls {
  display: flex;
  gap: 0.5rem;
}

.space-selector {
  padding: 0.5rem 1rem;
  border-bottom: 1px solid #e1e1e1;
}

.space-select {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #e1e1e1;
  border-radius: 4px;
  font-size: 0.9rem;
  background: white;
  box-sizing: border-box;
}

.space-select:focus {
  outline: none;
  border-color: #42b883;
}

/* 空间选项样式 */
.space-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0.25rem 0;
}

.space-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.space-name {
  font-weight: 600;
  color: #2c3e50;
  font-size: 0.9rem;
}

.space-desc {
  font-size: 0.75rem;
  color: #666;
  margin-top: 0.125rem;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.space-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 1px solid rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.space-right {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.space-count {
  font-size: 0.75rem;
  color: #999;
  background: #f0f0f0;
  padding: 0.125rem 0.375rem;
  border-radius: 8px;
  font-weight: 500;
  min-width: 20px;
  text-align: center;
}

.space-info {
  padding: 1rem;
  border-bottom: 1px solid #e1e1e1;
}

.space-details {
  margin-bottom: 1rem;
}

.space-details h4 {
  margin: 0 0 0.5rem 0;
  font-size: 1rem;
}

.space-description {
  margin: 0 0 0.5rem 0;
  color: #666;
  font-size: 0.85rem;
}

.space-stats {
  margin: 0;
  color: #888;
  font-size: 0.8rem;
}

.space-actions {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.create-doc-btn, .view-docs-btn {
  padding: 0.4rem 0.8rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.85rem;
  transition: all 0.3s;
}

.create-doc-btn {
  background: #42b883;
  color: white;
}

.create-doc-btn:hover {
  background: #369870;
}

.view-docs-btn {
  background: #74b9ff;
  color: white;
}

.view-docs-btn:hover {
  background: #0984e3;
}

.create-btn, .refresh-btn {
  padding: 0.4rem 0.8rem;
  background: #42b883;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.85rem;
  transition: background 0.3s;
}

.create-btn:hover, .refresh-btn:hover:not(:disabled) {
  background: #369870;
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}


.loading, .empty-state {
  padding: 2rem 1rem;
  text-align: center;
  color: #666;
}

.color-input {
  width: 60px !important;
  height: 40px;
  padding: 0;
  border: 1px solid #e1e1e1;
  cursor: pointer;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #999;
  padding: 0.25rem;
  border-radius: 4px;
  transition: all 0.2s;
}

.close-btn:hover {
  color: #666;
  background: #f5f5f5;
}

.dialog-form {
  padding: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #2c3e50;
  font-weight: 500;
  font-size: 0.9rem;
}

.form-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #e1e1e1;
  border-radius: 4px;
  font-size: 0.9rem;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #42b883;
}

.form-textarea {
  min-height: 80px;
  resize: vertical;
}

.form-select {
  background: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="8" viewBox="0 0 12 8"><path d="M6 8L0 2l1.41-1.41L6 5.17l4.59-4.58L12 2z" fill="%23666"/></svg>') no-repeat right 8px center;
  background-size: 12px;
  appearance: none;
}

.loading-text {
  font-size: 0.75rem;
  color: #999;
  margin: 0.25rem 0 0 0;
  font-style: italic;
}

.dialog-actions {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;
  margin-top: 1.5rem;
}

.cancel-btn, .submit-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f8f8f8;
  color: #666;
}

.cancel-btn:hover {
  background: #e8e8e8;
}

.submit-btn {
  background: #42b883;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background: #369870;
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>